package com.hospital.BaseActivity;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.*;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hospital.Common.CommonDao;
import com.hospital.Common.HttpAsyncXmlCallBack;
import com.hospital.Common.NetUtil;
import com.hospital.Entity.Person;
import com.hospital.KT_Activity.DoctorQueryActivity;
import com.hospital.KT_Activity.MenuManagerActivity;
import com.hospital.activity.R;
import com.hospital.adapter.HosSelectAdapter;
import com.hospital.adapter.MyTextAdapter;
import com.hospital.tools.HashMapMader;
import com.hospital.tools.MyApplication;
import com.hospital.tools.MyGestureDetector;
import com.hospital.tools.Util;
import com.hospital.xml.XMLMaker;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by wangjun on 2015/5/25.
 */
public class Base_Login  extends BaseActivity implements View.OnClickListener {

        private EditText mPhone;
        private EditText mPwd;
        private ProgressDialog mPd;
        private SharedPreferences mSp;
        private ImageView imagchacha,iamg1;
        private ScrollView scrollView1;
        private PopupWindow popBottom;
        private String locCity="";
        private TextView bottom;
        private LayoutInflater inflate;
        GestureDetector gestureDetector = null;
        private LinearLayout job_waiter_search_region;
       private List<HashMap<String, String>> tmp;
    //  private List<HashMap<String, String>> login;
       private CommonDao mCommonDao;

    private List<HashMap<String, String>> objects;
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            if (popBottom != null) {
                popBottom.dismiss();
                popBottom = null;
            }
        }




    @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.base_login);
            TextView findPwd = (TextView) findViewById(R.id.login_finPwd);
            TextView reg = (TextView) findViewById(R.id.login_toregister);
            mContext=this;
          //  mPageName="登陆页面";
            job_waiter_search_region = (LinearLayout) findViewById(R.id.job_waiter_search_region);
            job_waiter_search_region.setOnClickListener(this);
            imagchacha = (ImageView) findViewById(R.id.imagchacha);
            imagchacha.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                           // startActivity(new Intent(Base_Login.this, DropDownListActivity.class));
              //     startActivity(new Intent(Base_Login.this, IndexActivity.class));
              startActivity(new Intent(Base_Login.this, DoctorQueryActivity.class));

              //              startActivity(new Intent(Base_Login.this, DropDownListActivity.class));
                  startActivity(new Intent(Base_Login.this, MenuManagerActivity.class));

                    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                }
            });
            inflate = LayoutInflater.from(Base_Login.this);
            bottom=(TextView)findViewById(R.id.textView5);
            scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
            gestureDetector = new GestureDetector(this, new MyGestureDetector(this,scrollView1));
          //  location();
        objects=new ArrayList<HashMap<String, String>>();
      HashMap has=new HashMap();
        has.put("doc_name","裘森伟");
        has.put("hos_name","精神科");
        objects.add(has);
        has=new HashMap();
        has.put("doc_name","裘森伟2");
        has.put("hos_name","精神科2");
        objects.add(has);
          //  share = getSharedPreferences("user_msg", 0);
       //     checkUpdateRegion();
            mCommonDao = CommonDao.getInstance(this);
//	mCommonDao.clearAllRegions();
            //   initView();
        //    results = mCommonDao.getAllRegions();

//            if (results.isEmpty()) {
//                getData();
//            }
            	Util.softInputTouchListener(this,scrollView1);

//            imagchacha.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    onBackPressed();
//                }
//            });


            findPwd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (popBottom != null) {
                        popBottom.dismiss();
                    }
                    Util.hideSoftInput(scrollView1, Base_Login.this);

            //        getDocList();

               //     getDocList();

                    initcomplain();
//				Bundle bundle = new Bundle();
//				bundle.putString("url", Url.reset_company);
//				bundle.putBoolean("isUser", false);
//				startActivity(new Intent(LoginCompanyActivity.this, FindPwdActivity.class).putExtras(bundle));
//				overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                }
            });
            reg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                   startActivity(new Intent(Base_Login.this, RegisterActivity.class));
                    overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                }
            });
            mPhone = (EditText) findViewById(R.id.loginname);

            mPhone.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (popBottom != null) {
                        popBottom.dismiss();
                    }
                }
            });
            mPwd = (EditText) findViewById(R.id.login_pwd);
            mPwd.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    if (popBottom != null) {
                        popBottom.dismiss();
                    }
                }
            });
            scrollView1 = (ScrollView) findViewById(R.id.scrollView1);
            //	Util.softInputTouchListener(this,scrollView1);
            Button submit = (Button) findViewById(R.id.login_sub);
            submit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    sub();
                }
            });
            mSp = getSharedPreferences("user_msg", 0);

            iamg1=(ImageView)findViewById(R.id.imageView1);
            iamg1.setFocusable(true);
            iamg1.setFocusableInTouchMode(true);
            iamg1.requestFocus();
            iamg1.requestFocusFromTouch();
        }



    private void getDocList(){
        View view = inflate.inflate(R.layout.select_doc_list, null);
        ListView listView = (ListView) view.findViewById(R.id.search_gender_list);
        HosSelectAdapter ad=new HosSelectAdapter(Base_Login.this,objects);
        listView.setAdapter(ad);
        if (popBottom != null) {
            popBottom.dismiss();
        }
        TextView cancel = (TextView) view.findViewById(R.id.search_cancel);
        cancel.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (popBottom != null) {
                    popBottom.dismiss();
                }
            }
        });
        startPopBpttom(view);
    }

    private String[] tousu = {"对话框DEMO", "页卡+ListViewDemo","城市DEMO","表单DEMO"};
        private void initcomplain() {
            View view = inflate.inflate(R.layout.search_genderselect, null);
            ListView listView = (ListView) view.findViewById(R.id.search_gender_list);

        //   ArrayAdapter ad1= new ArrayAdapter<String>(Base_Login.this, R.layout.text_blue, tousu);
         //   listView.setAdapter(ad1);
           MyTextAdapter ad = new MyTextAdapter(Base_Login.this, R.layout.text_blue, tousu);

            listView.setAdapter(ad);
            Gson gson=new Gson();
            List<Person> persons = new ArrayList<Person>();
            for (int i = 0; i < 10; i++) {
                Person p = new Person();
                p.setName("name" + i);
                p.setAge(i * 5);
                persons.add(p);
            }
            String str = gson.toJson(persons);
            Log.i("tojson:",str);

          //Person person = gson.fromJson(str, Person.class);
            List<Person> ps = gson.fromJson(str, new TypeToken<List<Person>>(){}.getType());
            for(int i = 0; i < ps.size() ; i++)
            {
                Person p = ps.get(i);
                System.out.println("fromjson:"+p.toString());
            }
           // Company company=gson.fromJson(obj.toString(), Company.class);
            ad.setmOnItemClickListener(new MyTextAdapter.OnItemClickListener() {
                @Override
                public void onItemClick(int position) {
                    // TODO Auto-generated method stub

                    if (position ==0) {
                        Util.publishConfirm(Base_Login.this,Base_Login.this);
                    //    Bundle bundle = new Bundle();
                    //    bundle.putString("url", Url.reset_company);
                    //    bundle.putBoolean("isUser", false);
                      //  startActivity(new Intent(Base_Login.this, FindPwdActivity.class).putExtras(bundle));
                  //      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
//                    Bundle bundle = new Bundle();
//                    bundle.putInt("StatusId", complainId[position]);
//                    bundle.putInt("JobTypeId", typeId);
//                    bundle.putInt("jobId", jobId);
//
//                    startActivity(new Intent(LoginPersonActivity.this, TousuActivity.class).putExtras(bundle));

                    } else if(position==1) {
                       startActivity(new Intent(Base_Login.this, FrameManagerActivity.class));
                        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                   //     Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "15888193249"));
                   //     startActivity(intent);

                    }else if(position==2){

                        startActivity(new Intent(Base_Login.this, RootRegionActivity.class));
                        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);


                    }
                    else if(position==3){

                        startActivity(new Intent(Base_Login.this, CharDemoActivity.class));
                        overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);

                    }
                    if (popBottom != null) {
                        popBottom.dismiss();
                    }
                }
            });
            TextView cancel = (TextView) view.findViewById(R.id.search_cancel);
            cancel.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    if (popBottom != null) {
                        popBottom.dismiss();
                    }
                }
            });
            startPopBpttom(view);
        }





        private void startPopBpttom(View contentview) {
            popBottom = new PopupWindow(contentview, ActionBar.LayoutParams.WRAP_CONTENT, ActionBar.LayoutParams.WRAP_CONTENT, false);
            popBottom.setAnimationStyle(R.style.AnimBottom);
            popBottom.setFocusable(false);
            popBottom.setOutsideTouchable(true);

            if (popBottom.isShowing()) {
                // 隐藏窗口，如果设置了点击窗口外小时即不需要此方式隐藏
                popBottom.dismiss();
            } else {
                // 显示窗口
                int[] location = new int[2];
                bottom.getLocationOnScreen(location);

                popBottom.showAtLocation(bottom, Gravity.NO_GRAVITY, location[0], location[1] - popBottom.getHeight());
                //popBottom.showAtLocation(lin_bottom, Gravity.TOP, 0, 0);	//lin_bottom
                //  popupWindow.showAsDropDown();
            }


        }
        @Override
        protected void onStart() {
            super.onStart();
            Util.hideSoftInput(scrollView1,this);
        }

        public static void actionStart(Context context) {
            context.startActivity(new Intent(context, Base_Login.class));
        }

        private void sub() {
            final String phone = mPhone.getText().toString().trim();
            //   Constant.logphone1=mPhone.getText().toString();
           final String pwd = mPwd.getText().toString().trim();
            if ("".equals(phone)) {
                LayoutInflater inflater = getLayoutInflater();
                //通过制定XML文件及布局ID来填充一个视图对象
                View layout = inflater.inflate(R.layout.shibai, null);
                ImageView image = (ImageView) layout.findViewById(R.id.shibaiimga);
                //设置布局中图片视图中图片
                image.setImageResource(R.drawable.shibai);
                TextView text = (TextView) layout.findViewById(R.id.shibaitext);
                //设置内容
                text.setText("请输入用户名");

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
//			Toast  toast = Toast.makeText(getApplicationContext(),
//					"请核对手机号", Toast.LENGTH_LONG);
//			toast.setGravity(Gravity.CENTER, 0, 0);
//			LinearLayout toastView = (LinearLayout) toast.getView();
//			ImageView imageCodeProject = new ImageView(getApplicationContext());
//			imageCodeProject.setImageResource(R.drawable.shibai);
//			toastView.addView(imageCodeProject, 0);
//			toast.show();
                //		Util.showToast(this, "用户名为空");
                return;
            }
            if ("".equals(pwd) || pwd.length() < 6) {
                LayoutInflater inflater = getLayoutInflater();
                //通过制定XML文件及布局ID来填充一个视图对象
                View layout = inflater.inflate(R.layout.shibai, null);

                ImageView image = (ImageView) layout.findViewById(R.id.shibaiimga);
                //设置布局中图片视图中图片
                image.setImageResource(R.drawable.shibai);


                TextView text = (TextView) layout.findViewById(R.id.shibaitext);
                //设置内容
                text.setText("密码格式错误");

                Toast toast = new Toast(getApplicationContext());
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
//			Toast  toast = Toast.makeText(getApplicationContext(),
//					"密码格式错误", Toast.LENGTH_LONG);
//			toast.setGravity(Gravity.CENTER, 0, 0);
//			LinearLayout toastView = (LinearLayout) toast.getView();
//			ImageView imageCodeProject = new ImageView(getApplicationContext());
//			imageCodeProject.setImageResource(R.drawable.shibai);
//			toastView.addView(imageCodeProject, 0);
//			toast.show();
                //	Util.showToast(this, "密码为空");
                return;
            }

            //  String url = Url.login_Company;
            //     Constant.isUser = false;
            mPd = ProgressDialog.show(this, "提交中..", "正在登入..请稍后....", true, true);
            String xml = new XMLMaker("1", "1").getLoginInfo(phone, pwd);
            NetUtil.SoapWsProcessRunnable(xml,new HashMapMader().getLoginInfoMap(),new HttpAsyncXmlCallBack(){
                @Override
                public void onSuccess(List<HashMap<String, String>> login) {
                    if (mPd != null) mPd.dismiss();
                          if (login.size() < 1) {

                              Message msg = new Message();


                                  msg.arg1=-1;
                         //     }
                              handler.sendMessage(msg);

                          }

                              else if (login.get(0).get("ret_code").equals("0")) {
                                  String xml = new XMLMaker("1", "1").getMemberInfo(login.get(0).get(
                                          "member_num"));

                              ((MyApplication) Base_Login.this.getApplicationContext())
                                      .setMember_num(login.get(0).get("member_num"));
                              ((MyApplication) Base_Login.this.getApplicationContext())
                                      .setLogname(phone);
                              // add ln 20130130
                              ((MyApplication) Base_Login.this.getApplicationContext())
                                      .setPsw(pwd);
                                  NetUtil.SoapWsProcessRunnable(xml,new HashMapMader().getMemberInfoMap(),new HttpAsyncXmlCallBack(){
                                      @Override
                                      public void onSuccess(List<HashMap<String, String>> tmp) {

                                          Message msg = new Message();

                                          if (tmp.size() > 1) {
                                              msg.arg1=0;
                                              msg.obj=tmp;

                                          }else {
                                              msg.arg1=-1;
                                          }
                                          handler.sendMessage(msg);
                                      }
                                  });
                              }else{
                              Message msg = new Message();


                              msg.arg1=-2;
                              //     }
                              handler.sendMessage(msg);
                          }

                          }




            });




        }
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            switch (msg.arg1) {
                case -1:
                    LayoutInflater inflater = getLayoutInflater();
                    //通过制定XML文件及布局ID来填充一个视图对象
                    View layout = inflater.inflate(R.layout.shibai, null);

                    ImageView image = (ImageView) layout.findViewById(R.id.shibaiimga);
                    //设置布局中图片视图中图片
                    image.setImageResource(R.drawable.shibai);

                    TextView text = (TextView) layout.findViewById(R.id.shibaitext);
                    //设置内容
                    text.setText("网络错误");

                    Toast toast = new Toast(getApplicationContext());
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.setDuration(Toast.LENGTH_SHORT);
                    toast.setView(layout);
                    toast.show();
                    break;
                case 0:
                    List<HashMap<String, String>>  tmp1 = (List<HashMap<String, String>> ) msg.obj;
                    try {

                        ((MyApplication) Base_Login.this.getApplicationContext())
                                .setName(tmp1.get(0).get("name"));
                        ((MyApplication) Base_Login.this.getApplicationContext())
                                .setIdcard(tmp1.get(0).get("idcard"));
                        ((MyApplication) Base_Login.this.getApplicationContext())
                                .setTreatment_card(tmp1.get(0).get("treatment_card"));
                        ((MyApplication) Base_Login.this.getApplicationContext())
                                .setPhone(tmp1.get(0).get("phone"));
                        ((MyApplication) Base_Login.this.getApplicationContext())
                                .setAddress(tmp1.get(0).get("address"));
                      //  HealthAct.NAME = tmp1.get(0).get("name");
                      //  HealthAct.ID_CARD = tmp1.get(0).get("idcard");


//                        ((MyApplication) Base_Login.this.getApplicationContext())
//                                .setLongin(true);
 //                       startActivity(new Intent(Base_Login.this, UserInfoIndexAct.class));
  //                      overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out);
                     //   Intent intent=new Intent();
                     //   intent.setClass(Base_Login.this,UserInfoIndexAct.class);
                     //   startActivity(intent);
                      //  Base_Login.this.finish();

                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 1:
                    JSONObject obj = (JSONObject) msg.obj;
                    try {
                        // results = JSON.parseObject(obj.getString("results").toString(), new TypeReference<List<Region>>() {
                        //  });
                        //  mCommonDao.clearAllRegions();
                        //	Log.i("1222222222",obj.getString("results").toString());
                        //  mCommonDao.batchAddRegions(results);
                        //     convertRegions(results);

                        //      location();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case -2:
                    inflater = getLayoutInflater();
                     layout = inflater.inflate(R.layout.shibai, null);

                    image = (ImageView) layout.findViewById(R.id.shibaiimga);
                    //设置布局中图片视图中图片
                    image.setImageResource(R.drawable.shibai);

                     text = (TextView) layout.findViewById(R.id.shibaitext);
                    //设置内容
                    text.setText("用户名密码错误");

                     toast = new Toast(getApplicationContext());
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.setDuration(Toast.LENGTH_SHORT);
                    toast.setView(layout);
                    toast.show();
                    break;
                default:
                    break;
            }
        }
    };
}

